
import 'dart:io';

import 'package:framelib/config/app_config.dart';
import 'package:framelib/net/base_entity.dart';
import 'package:framelib/net/request_manage.dart';
import 'net/comm_api.dart';
import 'package:dio/dio.dart';

class CommService{
//获取oss上传链接
  Future<BaseEntity> getUploadUrl({Map<String, dynamic>? parmsMap}) async{
    BaseEntity baseEntity = await RequestManage.instance.get(
        CommApi.instance.getUploadUrl,
        isFormData: false,
        queryParameters: parmsMap,
        // isReturnAll: true,
        fromJsonFunc: (json)=>json
    );
    return baseEntity;
  }
  //获取文件临时地址
  Future<BaseEntity> getTempFileByFileKey({required String fileKey}) async{
    BaseEntity baseEntity = await RequestManage.instance.get(
        CommApi.instance.getFileByFileKey,
        isFormData: false,
        queryParameters: {'fileKey':fileKey},
        // isReturnAll: true,
        fromJsonFunc: (json)=>json
    );
    return baseEntity;
  }

  //上传文件
  Future<BaseEntity> uploadFile({required String uploadUrl,required String fileName,required File file}) async{
    print('uploadFile--->fileName=$fileName');
    var options = BaseOptions(
      connectTimeout: Duration(milliseconds: 15000),
      receiveTimeout: Duration(milliseconds: 15000),
      responseType: ResponseType.plain,
      validateStatus: (status){
        // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
        return true;
      },
      headers: {
        'Content-Disposition':'attachment;filename=${Uri.encodeComponent(fileName)}',
        'Content-Type': 'application/octet-stream',
      },
      contentType: 'application/octet-stream',
    );
    Dio _dioUp = Dio(options);
    Response? response;
    try{
      response = await _dioUp.put(uploadUrl,data: file.readAsBytesSync());
      if(response?.statusCode == 200){
        return BaseEntity(code: AppConfig.instance.SUCCESS_CODE,msg: '上传成功');
      }else{
        return BaseEntity(code: 201,msg: '上传失败');
      }
    }catch(e){
      return BaseEntity(code: 201,msg: '上传失败');
    }
  }

  //login 接口
  Future<BaseEntity> login({Map<String, dynamic>? parmsMap}) async {
    BaseEntity baseEntity = await RequestManage.instance.post(
        CommApi.instance.login,
        data: parmsMap,
        isReturnAll: true,
        fromJsonFunc: (json)=>json
    );
    return baseEntity;
  }

}